package com.example.easypoi.service.impl;

import com.example.easypoi.mapper.AreaMapper;
import com.example.easypoi.model.Area;
import com.example.easypoi.service.AreaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AreaServiceImpl implements AreaService {

    @Resource
    private AreaMapper areaMapper;

    @Override
    public List<Area> regionList() {
        //计算sql执行的额时间
        long start = System.currentTimeMillis();
        //查询出所有的省市区信息
        List<Area> regionList = areaMapper.findAll();
        //给省下一级 添加市  所以将省和市作为 value 将parent_id 作为省和市的key 放入Map
        Map<String, Area> provinceMap = new HashMap<>();
        Map<String, Area> cityMap = new HashMap<>();
        for (Area region : regionList) {
            if (region.getLevel() == 1) {
                // 当前region是省 放入省map
                provinceMap.put(region.getId(), region);
            } else if (region.getLevel() == 2) {
                // 当前region是市 放入市map
                cityMap.put(region.getId(), region);
            }
        }
        List<Area> provinceList = new ArrayList<>();
        for (Area region : regionList) {
            if (region.getLevel() == 2) {
                // 这是市 获取到市的 父code,然后从 省map中获取到省对象,然后将当前 市放入省的children
                String provinceCode = region.getParentId();
                // 获取当前市的 父级别 省的对象
                Area province = provinceMap.get(provinceCode);
                // 将市对象 添加到 省对象
                province.getChildren().add(region);
            } else if (region.getLevel() == 3) {
                String cityCode = region.getParentId();
                Area city = cityMap.get(cityCode);
                city.getChildren().add(region);
            } else {
                provinceList.add(region);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时毫秒数:" + (end - start));
        return provinceList;
    }
}
